<template>
  <div class="admin-user-money-page">
    <div class="page-header">
      <h1>修改用户余额</h1>
      <el-button @click="goBack">返回列表</el-button>
    </div>

    <el-skeleton :rows="5" animated v-if="loading" />

    <el-card class="form-card" v-else-if="user">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户ID">{{ user.id }}</el-descriptions-item>
        <el-descriptions-item label="用户账号">{{ user.userAccount }}</el-descriptions-item>
        <el-descriptions-item label="当前余额">
          <span class="current-balance">¥ {{ user.balance.toFixed(2) }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider />

      <el-form label-width="100px" class="recharge-form">
        <el-form-item label="充值金额" required>
          <el-input-number
              v-model="rechargeAmount"
              :precision="2"
              :step="100"
              :min="0"
              controls-position="right"
              style="width: 100%;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="handleRecharge">确认充值</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-empty description="无法找到该用户信息" v-else />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUserByIdApi, updateUserBalanceApi } from '../../api/user';

const route = useRoute();
const router = useRouter();
const userId = Number(route.params.id); // 从路由参数获取用户ID

const loading = ref(true);
const submitting = ref(false);
const user = ref(null);
const rechargeAmount = ref(0);

// 获取用户信息
const fetchUser = async () => {
  if (!userId) {
    ElMessage.error('无效的用户ID');
    loading.value = false;
    return;
  }
  loading.value = true;
  try {
    user.value = await getUserByIdApi(userId);
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  } finally {
    loading.value = false;
  }
};

// 处理充值
const handleRecharge = async () => {
  if (rechargeAmount.value <= 0) {
    ElMessage.warning('充值金额必须大于0');
    return;
  }

  ElMessageBox.confirm(`确定要为用户【${user.value.userAccount}】充值 ${rechargeAmount.value.toFixed(2)} 元吗？`, '充值确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    submitting.value = true;
    try {
      const payload = {
        userId: userId,
        amount: rechargeAmount.value,
      };
      await updateUserBalanceApi(payload);
      ElMessage.success('充值成功！');
      // 成功后刷新当前页面的用户信息
      await fetchUser();
      rechargeAmount.value = 0; // 重置输入框
    } catch (error) {
      console.error('充值失败:', error);
      ElMessage.error('充值操作失败');
    } finally {
      submitting.value = false;
    }
  }).catch(() => {
    // 用户取消操作
  });
};

const goBack = () => {
  // 返回到用户列表页，您可以根据需要修改路径
  router.push('/admin/users');
};

onMounted(() => {
  fetchUser();
});
</script>

<style scoped>
.admin-user-money-page {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-header h1 {
  font-size: 24px;
  margin: 0;
}
.form-card {
  max-width: 600px;
  margin: 0 auto;
}
.current-balance {
  font-size: 18px;
  color: #E6A23C;
  font-weight: bold;
}
.recharge-form {
  margin-top: 20px;
}
</style>